<template>
  <div class="order-list-container">
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" class="search-form-content">
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="拍卖品标题">
          <el-input v-model="queryParams.auctionTitle" placeholder="请输入拍卖品标题" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
            <el-option label="待付款" value="0" />
            <el-option label="待发货" value="1" />
            <el-option label="待收货" value="2" />
            <el-option label="已完成" value="3" />
            <el-option label="已取消" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchOrders">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="序号" width="120" />
z      <el-table-column prop="number" label="订单编号" width="200" />
      <el-table-column prop="auctionTitle" label="拍卖品" min-width="150">
      </el-table-column>
      <el-table-column prop="orderAmount" label="成交金额" width="120">
        <template #default="scope">
          <span class="price">￥{{ scope.row.orderAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="120">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
            {{ getOrderStatusText(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button @click="viewOrderDetail(scope.row.id)" type="primary" size="small">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total"
        layout="total, sizes, prev, pager, next, jumper" />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="50%" destroy-on-close>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ orderDetail.number }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ orderDetail.auctionTitle }}</el-descriptions-item>
        <el-descriptions-item label="商品图片">
          <el-image style="width: 200px; height: 200px" :src="orderDetail.auctionImage" fit="cover"
            :preview-src-list="[orderDetail.auctionImage]"></el-image>
        </el-descriptions-item>
        <el-descriptions-item label="成交价格">
          <span class="price">￥{{ orderDetail.orderAmount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(orderDetail.orderStatus)">
            {{ getOrderStatusText(orderDetail.orderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="买家">{{ orderDetail.buyerName }}</el-descriptions-item>
        <el-descriptions-item label="卖家">{{ orderDetail.sellerName }}</el-descriptions-item>
        <el-descriptions-item label="收货人信息">
          <div>姓名：{{ orderDetail.consignee }}</div>
          <div>电话：{{ orderDetail.phone }}</div>
          <div>地址：{{ orderDetail.address }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(orderDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间" v-if="orderDetail.payTime">{{ formatDate(orderDetail.payTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="发货时间" v-if="orderDetail.deliveryTime">{{
          formatDate(orderDetail.deliveryTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="完成时间" v-if="orderDetail.finishTime">{{ formatDate(orderDetail.finishTime)
          }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAllOrders, getOrderDetailAdmin } from '@/api/order' // 导入getOrderDetailAdmin

export default {
  name: 'OrderList',
  setup() {
    const router = useRouter()
    const tableData = ref([])
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 查询参数
    const queryParams = reactive({
      orderNo: '',
      orderStatus: '',
      auctionTitle: '' // 添加拍卖品标题查询参数
    })

    // 加载订单数据
    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          orderNo: queryParams.orderNo || null,
          orderStatus: queryParams.orderStatus || null,
          auctionTitle: queryParams.auctionTitle || null, // 传递拍卖品标题参数
          page: currentPage.value,
          pageSize: pageSize.value
        }

        const res = await getAllOrders(params.page, params.pageSize, params.auctionTitle, params.orderNo, params.orderStatus)

        if (res.code === 1) {
          tableData.value = res.data.records || []
          total.value = res.data.total || 0
        } else {
          ElMessage.error(res.msg || '加载订单数据失败，请稍后重试')
        }
      } catch (error) {
        console.error('加载订单列表失败:', error)
        ElMessage.error('加载数据失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    // 获取订单状态文本
    const getOrderStatusText = (status) => {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消',
      }
      return statusMap[status] || '未知状态'
    }

    // 获取订单状态类型
    const getOrderStatusType = (status) => {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'danger',
      }
      return typeMap[status] || ''
    }

    // 查询订单
    const searchOrders = () => {
      currentPage.value = 1
      loadData()
    }

    // 重置查询
    const resetQuery = () => {
      queryParams.orderNo = ''
      queryParams.orderStatus = ''
      searchOrders()
    }

    // 刷新数据
    const refreshData = () => {
      currentPage.value = 1
      loadData()
    }

    // 改变每页显示数量
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadData()
    }

    // 改变页码
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadData()
    }

    // 订单详情相关
    const detailDialogVisible = ref(false)
    const orderDetail = ref({})

    // 查看订单详情
    const viewOrderDetail = async (orderId) => {
      try {
        const response = await getOrderDetailAdmin(orderId) // 调用getOrderDetailAdmin
        if (response.code === 1) {
          orderDetail.value = response.data
          detailDialogVisible.value = true
        } else {
          throw new Error(response.msg || '获取订单详情失败')
        }
      } catch (error) {
        console.error('获取订单详情失败', error)
        ElMessage.error('获取订单详情失败，请稍后再试')
      }
    }

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
    }

    onMounted(() => {
      loadData()
    })

    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      queryParams,
      loadData,
      refreshData,
      handleSizeChange,
      handleCurrentChange,
      viewOrderDetail,
      getOrderStatusText,
      getOrderStatusType,
      searchOrders,
      resetQuery,
      detailDialogVisible, // 暴露详情对话框状态
      orderDetail, // 暴露订单详情数据
      formatDate // 暴露格式化日期方法
    }
  }
}
</script>

<style scoped>
.order-list-container {
  padding: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>